import upload from "./upload.js";
let updateDialog, form;
fetch("country-update.html").then(r => r.text()).then(text => {
	updateDialog = $(text);
	console.debug(updateDialog);
	$("body").append(updateDialog);

	form = updateDialog[0].querySelector("form");//form是原生标签元素,非jquery对象

	let btn = updateDialog[0].querySelector("._save");

	console.debug(updateDialog, form, btn);
	btn.onclick = function() {
		//验证输入参数
		let param = new URLSearchParams(new FormData(form));
		console.info(param.toString());
		fetch("country-update.let", {
			method: 'POST', // *GET, POST, PUT, DELETE, etc.
			mode: 'cors', // no-cors, *cors, same-origin
			cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
			credentials: 'include', // include, *same-origin, omit
			headers: {
				// 'Content-Type': 'application/json'
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			redirect: 'follow', // manual, *follow, error
			referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
			// body: JSON.stringify(data) // body data type must match "Content-Type" header
			body: param
		}).then(r => r.json()).then(data => {
			console.debug(data);
			if (data.ok) {
				updateDialog.modal('hide');
				window.postMessage("loadData");//发送消息
			} else {
				alert(data.msg);
			}
		}).catch(e => {
			console.error(e);
		});
	}
});

export default function(item) {
	updateDialog.modal('show');
	// form.countryName.value=item.countryName;
	// form["countryName"].value=item["countryName"];
	for (let name in item) {
		form[name].value = item[name];
	}

	upload(updateDialog.find("._upload")[0], function(data) {
		form.countryUri.value = data.uri;
	}, "../demo/down.let?file=" + item.countryUri);

}
